from flask import Flask, render_template, request, session, copy_current_request_context
from datetime import datetime
from hello import s4l
from DBcm import UseDatabase, ConnectionError, CredentialsError, SQLError
from checker import check_logged_in
from threading import Thread


app = Flask(__name__)

dbconfig = 'vsearchlogDB.db'

u = UseDatabase(dbconfig)


@app.route('/search4', methods=['POST'])
def do_search() -> 'html':

    @copy_current_request_context
    def log_request(req: 'flask_request', res: str) -> None:
        try:
            with u as cursor:
                cursor.execute("""CREATE TABLE IF NOT EXISTS log (
                    data text NOT NULL,
                    phrase varchar(128) NOT NULL,
                    letters varchar(32) NOT NULL,
                    ip varchar(16) NOT NULL,
                    browser_string varchar(256) NOT NULL,
                    result varchar(64) NOT NULL
                    )""")

                cursor.execute(
                    """INSERT INTO log (data, phrase, letters, ip, browser_string,
                    result) VALUES (?, ?, ?, ?, ?, ?)""",
                    (datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                     req.form['phrase'],
                     req.form['letters'],
                     req.remote_addr,
                     req.headers.get('User-Agent'),
                     res,))
        except Exception as err:
            print('Some shit happens', str(err))

    phrase = request.form['phrase']
    letters = request.form['letters']
    title = 'Here are your result:'
    results = str(s4l(phrase, letters))
    try:
        t = Thread(target=log_request, args=(request, results))
        t.start()
    except Exception as err:
        print('***** Logging failed with this error:', str(err))
    return render_template('results.html',
                           the_title=title,
                           the_phrase=phrase,
                           the_letters=letters,
                           the_results=results,)


@app.route('/')
@app.route('/entry')
def entry_page() -> 'html':
    return render_template('entry.html',
                           the_title='Welcome to search4letters on the web!')


@app.route('/viewlog')
@check_logged_in
def view_the_log() -> 'html':
    try:
        with u as cursor:
            _SQL = """SELECT data, phrase, letters, ip, browser_string,
            result FROM log"""
            cursor.execute(_SQL)
            contents = cursor.fetchall()
            titles = ('Data', 'Phrase', 'Letters',
                      'Remote_addr', 'User_agent', 'Result')

            return render_template('viewlog.html',
                                   the_title='View Log',
                                   the_row_titles=titles,
                                   the_data=contents,)

    except ConnectionError as err:
        print('SQLite InterfaceError:', str(err))
    except CredentialsError as err:
        print('User-id/Password issue. Error:', str(err))
    except SQLError as err:
        print('Is your query correct? Error:', str(err))
    except Exception as err:
        print('Something went wrong:', str(err))


@app.route('/login')
def do_login() -> 'html':
    return render_template('passw.html', the_title='Enter your password.')


@app.route('/passwallow', methods=['POST'])
def check_login() -> 'html':
    if request.form['passw'] != app.secret_key:
        checkin = 'incorrect'
        title = 'You are enter wrong password.'
    else:
        checkin = 'correct'
        title = 'You are now logged in.'
        session['logged_in'] = True
    return render_template('passwallow.html',
                           the_checkin=checkin,
                           the_title=title,
                           )


@app.route('/logout')
def do_logout() -> str:
    session.pop('logged_in', None)
    return 'You are now logged out'


app.secret_key = 'WillKey'


if __name__ == '__main__':
    app.run(debug=True)
